﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using RecordTime.Models;
using RecordTime.ProjectManagement.ViewModels;

namespace RecordTime.Infrastructure.Mapping
{
    [Export(typeof(IMappingService))]
    public class MappingService : IMappingService
    {
        public MappingService()
        {
            //DTO Models to ViewModels
            AutoMapper.Mapper.CreateMap<TaskViewModel, Task>()
                .ForMember(m => m.Project, opt => opt.MapFrom(vm => vm.Projects.FirstOrDefault(x => x.ProjectId == vm.ProjectId)));
            AutoMapper.Mapper.CreateMap<Task, TaskViewModel>()
                .ForMember(vm => vm.Projects, opt => opt.Ignore())
                .ForMember(vm => vm.ProjectId, opt => opt.MapFrom(m => m.Project.ProjectId));

            //DAO Entity Framework to Models
            AutoMapper.Mapper.CreateMap<Task, Data.Task>();
            AutoMapper.Mapper.CreateMap<Data.Task, Task>();

            AutoMapper.Mapper.CreateMap<Project, Data.Project>();
            AutoMapper.Mapper.CreateMap<Data.Project, Project>();
        }

        public Task Get(TaskViewModel taskViewModel)
        {
            return AutoMapper.Mapper.Map<TaskViewModel, Task>(taskViewModel);
        }

        public TaskViewModel Get(Task task)
        {
            return AutoMapper.Mapper.Map<Task, TaskViewModel>(task);
        }

        public Data.Task GetEntity(Task task)
        {
            return AutoMapper.Mapper.Map<Task, Data.Task>(task);
        }

        public IEnumerable<Task> GetAll(IEnumerable<Data.Task> tasks)
        {
            return AutoMapper.Mapper.Map<IEnumerable<Data.Task>, IEnumerable<Task>>(tasks);
        }
    }
}